import React, { Fragment, useContext, useEffect, useState, useRef } from "react";
import { useRouter } from 'next/router';
import CartContext from "../../../../helpers/cart";
import { CompareContext } from "../../../../helpers/Compare/CompareContext";
import { CurrencyContext } from "../../../../helpers/Currency/CurrencyContext";
import { WishlistContext } from "../../../../helpers/wishlist/WishlistContext";
import { Container, Row, Col, Button, Dropdown } from "reactstrap";
import ProductItem from "../../../../components/common/product-box/ProductBox12";

import { getProductsFilter, getProducts, addProductToCart, getAllProducts } from "../../../../api/api";
import { fileServerUrl } from "../../../../config/index.json";
import { toast } from "react-toastify";
import Loading from "../../../../components/common/Loading";

const ParallaxSlider = () => {
  const context = useContext(CartContext);
  const router = useRouter();
  const { year, brand, model, engine, fuelType } = router.query;  // 获取查询参数
  const compareContext = useContext(CompareContext);
  const curContext = useContext(CurrencyContext);
  const wishListContext = useContext(WishlistContext);
  const [yearList, setYearList] = useState([]);
  const [brandList, setBrandList] = useState([]);
  const [modelList, setModelList] = useState([]);
  const [engineList, setEngineList] = useState([]);
  const [fuelTypeList, setFuelTypeList] = useState([]);

  // const [yearDisable, setYearDisable] = useState(false);
  const [brandDisable, setBrandDisable] = useState(true);
  const [modelDisable, setModelDisable] = useState(true);
  const [engineDisable, setEngineDisable] = useState(true);
  const [fuelTypeDisable, setFuelTypeDisable] = useState(true);
  const [searchable, setSearchable] = useState(true);
  const [isLoading, setIsloading] = useState(false);

  const yearInput = useRef("");
  const brandInput = useRef("");
  const modelInput = useRef("");
  const engineInput = useRef("");
  const fuelTypeInput = useRef("");

  const [pageNum, setPageNum] = useState(1);
  const [productList, setProductList] = useState([]);
  const [pageCount, setPageCount] = useState(1);

  const batchSetDisable = (id) => {
    if (id == 'year') {
      // setBrandDisable(true);
      setModelDisable(true);
      setEngineDisable(true);
      setFuelTypeDisable(true);
    }
    else if (id == "brand") {
      // setModelDisable(true);
      setEngineDisable(true);
      setFuelTypeDisable(true);
    }
    else if (id == "model") {
      // setEngineDisable(true);
      setFuelTypeDisable(true);
    }
  }

  const onYearOptionChange = (e) => {
    yearInput.current = e.target.value;

    setBrandDisable(false);
    brandInput.current = "defaultOption";
    // document.getElementById("brand").value = "defaultOption";
    modelInput.current = "defaultOption";
    // document.getElementById("model").value = "defaultOption";
    engineInput.current = "defaultOption";
    // document.getElementById("engine").value = "defaultOption";
    fuelTypeInput.current = "defaultOption";
    // document.getElementById("fuelType").value = "defaultOption";
    batchSetDisable("year");
    var input = {
      "filterType": "brand",
      "year": e.target.value,
      "brand": "",
      "model": "",
      "engine": "",
      "fuelType": ""
    };
    setSearchable(true);
    getProductsFilter(input).then(res => {
      setBrandList(res.data);
    })
  }

  const onBrandOptionChange = (e) => {
    brandInput.current = e.target.value;

    setModelDisable(false);
    modelInput.current = "defaultOption";
    // document.getElementById("model").value = "defaultOption";
    engineInput.current = "defaultOption";
    // document.getElementById("engine").value = "defaultOption";
    fuelTypeInput.current = "defaultOption";
    // document.getElementById("fuelType").value = "defaultOption";
    batchSetDisable("brand");
    var input = {
      "filterType": "model",
      "year": yearInput.current,
      "brand": e.target.value,
      "model": "",
      "engine": "",
      "fuelType": ""
    };
    setSearchable(true);
    getProductsFilter(input).then(res => {
      setModelList(res.data);
    })
  }

  const onModelOptionChange = (e) => {
    modelInput.current = e.target.value;

    setEngineDisable(false);
    engineInput.current = "defaultOption";
    // document.getElementById("engine").value = "defaultOption";
    fuelTypeInput.current = "defaultOption";
    // document.getElementById("fuelType").value = "defaultOption";
    batchSetDisable("model");
    var input = {
      "filterType": "engine",
      "year": yearInput.current,
      "brand": brandInput.current,
      "model": e.target.value,
      "engine": "",
      "fuelType": ""
    };
    setSearchable(true);
    getProductsFilter(input).then(res => {
      setEngineList(res.data);
    })
  }

  const onEngineOptionChange = (e) => {
    engineInput.current = e.target.value;
    setFuelTypeDisable(false);
    fuelTypeInput.current = "defaultOption";
    // document.getElementById("fuelType").value = "defaultOption";
    batchSetDisable("engine");
    var input = {
      "filterType": "fuelType",
      "year": yearInput.current,
      "brand": brandInput.current,
      "model": modelInput.current,
      "engine": e.target.value,
      "fuelType": ""
    };
    setSearchable(true);
    getProductsFilter(input).then(res => {
      setFuelTypeList(res.data);
    })
  }

  const onFuelTypeOptionChange = (e) => {
    fuelTypeInput.current = e.target.value;
    if (e.target.value != "" && e.target.value != "defaultOption") {
      setSearchable(false);
    }
    else {
      setSearchable(true);
    }
  }

  const onSearchBtnClick = () => {
    setIsloading(true);
    getProducts({
      "year": yearInput.current,
      "brand": brandInput.current,
      "model": modelInput.current,
      "engine": engineInput.current,
      "fuelType": fuelTypeInput.current,
      "pageNum": 1,
      "pageSize": 10
    }).then(res => {
      setPageNum(1);
      setPageCount(res.page_count);
      setProductList(res.data);
      setIsloading(false);
    })
  }

  const searchNextPage = () => {
    setIsloading(true);
    if (pageNum < pageCount) {
      if (yearInput.current == "" && brandInput.current == "" && modelInput.current == "" && engineInput.current == "" && fuelTypeInput.current == "") {
        getAllProducts({
          "pageNum": pageNum + 1,
          "pageSize": 10
        }).then(res => {
          setPageNum(pageNum + 1);
          setPageCount(res.page_count);
          setProductList(res.data);
          setIsloading(false);
        })
      }
      else {
        getProducts({
          "year": yearInput.current,
          "brand": brandInput.current,
          "model": modelInput.current,
          "engine": engineInput.current,
          "fuelType": fuelTypeInput.current,
          "pageNum": pageNum + 1,
          "pageSize": 10
        }).then(res => {
          setPageNum(pageNum + 1);
          setPageCount(res.page_count);
          setProductList(res.data);
          setIsloading(false);
        })
      }
    }
  }

  const searchLastPage = () => {
    setIsloading(true);
    if (pageNum > 1) {
      if (yearInput.current == "" && brandInput.current == "" && modelInput.current == "" && engineInput.current == "" && fuelTypeInput.current == "") {
        getAllProducts({
          "pageNum": pageNum - 1,
          "pageSize": 10
        }).then(res => {
          setPageNum(pageNum - 1);
          setPageCount(res.page_count);
          setProductList(res.data);
          setIsloading(false);
        })
      }
      else {
        getProducts({
          "year": yearInput.current,
          "brand": brandInput.current,
          "model": modelInput.current,
          "engine": engineInput.current,
          "fuelType": fuelTypeInput.current,
          "pageNum": pageNum - 1,
          "pageSize": 10
        }).then(res => {
          setPageNum(pageNum - 1);
          setPageCount(res.page_count);
          setProductList(res.data);
          setIsloading(false);
        })
      }
    }
  }

  const handleAddProductToCart = (dataitem) => {
    var user = localStorage.getItem("XYCLogin");
    if (user) {

      var input = {
        "product_id": dataitem.product_id,
        "quantity": "1",
        "user_guid": JSON.parse(user).user_guid
      };
      addProductToCart(input).then(res => {
        if (res.error_code == "2000") {
          toast.success(res.msg);
          localStorage.setItem('cartNum', parseInt(localStorage.getItem('cartNum')) + 1);
        }
        else {
          toast.warning(res.msg);
        }
      })
    }
    else {
      toast.error("Please Login To Shopping!")
    }
  }

  useEffect(() => {
    var input = {
      "filterType": "year",
      "year": "",
      "brand": "",
      "model": "",
      "engine": "",
      "fuelType": ""
    };
    getProductsFilter(input).then(res => {
      setYearList(res.data);
    });
    if (year && brand && engine && model && fuelType) {
      setIsloading(true);
      setBrandDisable(false);
      setEngineDisable(false);
      setModelDisable(false);
      setFuelTypeDisable(false);
      setSearchable(false);
      yearInput.current = year;
      brandInput.current = brand;
      modelInput.current = model;
      engineInput.current = engine;
      fuelTypeInput.current = fuelType;

      setBrandList([brand]);
      setEngineList([engine]);
      setModelList([model]);
      setFuelTypeList([fuelType])
      getProducts({
        "year": year,
        "brand": brand,
        "model": model,
        "engine": engine,
        "fuelType": fuelType,
        "pageNum": 1,
        "pageSize": 10
      }).then(res => {
        setPageNum(1);
        setPageCount(res.page_count);
        setProductList(res.data);
        setIsloading(false);
      })
    }
    else {
      setIsloading(true);
      getAllProducts({
        "pageNum": 1,
        "pageSize": 10
      }).then(res => {
        setPageNum(1);
        setPageCount(res.page_count);
        setProductList(res.data);
        setIsloading(false);
      })
    }
  }, [])

  return (
    <Fragment>
      <section className="full-banner parallax small-slider tools-parallax-product">
        <Container>
          <Row style={{ marginLeft: 120 }}>
            <Col lg="2">
              <div className="tools-description">
                <div>
                  <h3><span style={{ color: 'red' }}>*</span>Category</h3>
                  <div className="tools-form">
                    <div className="search-box">
                      <select name="year" id="year" className="form-control" onChange={onYearOptionChange} value={yearInput.current || (year || "defaultOption")}>
                        <option value="defaultOption">Year</option>
                        {
                          yearList.map(item => {
                            return <option value={item}>{item}</option>
                          })
                        }
                      </select>
                    </div>
                    <div className="search-box">
                      <select name="brand" id="brand" className="form-control" onChange={onBrandOptionChange} disabled={brandDisable} value={brandInput.current || (brand || "defaultOption")}>
                        <option value="defaultOption">Brand</option>
                        {
                          brandList.map(item => {
                            return <option value={item}>{item}</option>
                          })
                        }
                      </select>
                    </div>
                    <div className="search-box">
                      <select name="model" id="model" className="form-control" onChange={onModelOptionChange} disabled={modelDisable} value={modelInput.current || (model || "defaultOption")}>
                        <option value="defaultOption">Model</option>
                        {
                          modelList.map(item => {
                            return <option value={item}>{item}</option>
                          })
                        }
                      </select>
                    </div>
                    <div className="search-box">
                      <select name="engine" id="engine" className="form-control" onChange={onEngineOptionChange} disabled={engineDisable} value={engineInput.current || (engine || "defaultOption")}>
                        <option value="defaultOption">Engine</option>
                        {
                          engineList.map(item => {
                            return <option value={item}>{item}</option>
                          })
                        }
                      </select>
                    </div>
                    <div className="search-box">
                      <select name="fuelType" id="fuelType" className="form-control" onChange={onFuelTypeOptionChange} disabled={fuelTypeDisable} value={fuelTypeInput.current || (fuelType || "defaultOption")}>
                        <option value="defaultOption">Fuel Type</option>
                        {
                          fuelTypeList.map(item => {
                            return <option value={item}>{item}</option>
                          })
                        }
                      </select>
                    </div>
                    <div className="search-button">
                      <Button className="btn btn-solid btn-find" disabled={searchable} onClick={onSearchBtnClick}>
                        Search
                      </Button>
                      {/* <a className="btn btn-solid btn-find" onClick={onSearchBtnClick} >
                        
                      </a> */}
                    </div>
                  </div>
                </div>
              </div>
            </Col>
            <Col lg="8" className="tools-grey ratio_square">
              {/* TODO:添加排序 */}
              <Dropdown
                data={[
                  { name: 'productId', value: 'PRODUCT_ID' },
                  { name: 'productId', value: 'PRODUCT_PRICE' }
                ]}
                active={true}
                Direction="start"
                name="DropDown"
              />
              {/* loading */}
              {isLoading ? <Row style={{ height: 500 }}>
                <Loading />
              </Row> :
                <>
                  <Row>
                    {productList.length > 0 &&
                      productList.slice(0, 5).map((dataitem, i) => {
                        dataitem.key = i;
                        return (
                          <>
                            <Col style={{ width: '25%' }}>
                              <ProductItem
                                product={dataitem}
                                key={i}
                                spanClass={true}
                                addToCompare={() => compareContext.addToCompare(dataitem)}
                                addCart={() => handleAddProductToCart(dataitem)}
                                addWishlist={() => wishListContext.addToWish(dataitem)}
                                fileServerUrl={fileServerUrl}
                              />
                            </Col>
                          </>
                        );
                      })
                    }
                    {
                      productList.length > 0 && productList.length < 5 && Array.from({ length: (5 - productList.length) }).map(() => {
                        return (
                          <>
                            <Col style={{ width: '25%' }}>
                            </Col>
                          </>
                        )
                      })
                    }
                  </Row>
                  <Row>
                    {productList.length > 5 &&
                      productList.slice(5, 10).map((dataitem, i) => {
                        return (
                          <>
                            <Col style={{ width: '25%' }}>
                              <ProductItem
                                product={dataitem}
                                key={i}
                                spanClass={true}
                                addToCompare={() => compareContext.addToCompare(dataitem)}
                                addCart={() => handleAddProductToCart(dataitem)}
                                addWishlist={() => wishListContext.addToWish(dataitem)}
                                fileServerUrl={fileServerUrl}
                              />
                            </Col>
                          </>
                        );
                      })
                    }
                    {
                      productList.length > 5 && productList.length < 10 && Array.from({ length: (10 - productList.length) }).map(() => {
                        return (
                          <>
                            <Col style={{ width: '25%' }}>
                            </Col>
                          </>
                        )
                      })
                    }
                  </Row>
                </>
              }



              {/* <Slider
                {...tools_product_4}
                className="tools-product-4 product-m"
              >
                {productList.length > 0 &&
                  productList.slice(0, 5).map((dataitem, i) => {
                    dataitem.key = i;
                    return (
                      <>
                        <ProductItem
                          product={dataitem}
                          key={i}
                          spanClass={true}
                          addToCompare={() => compareContext.addToCompare(dataitem)}
                          addCart={() => handleAddProductToCart(dataitem)}
                          addWishlist={() => wishListContext.addToWish(dataitem)}
                          fileServerUrl={fileServerUrl}
                        />
                      </>
                    );
                  })
                }
              </Slider> */}
              {/* <Slider
                {...tools_product_4}
                className="tools-product-4 product-m"
              >
                {productList.length > 5 &&
                  productList.slice(5, 10).map((dataitem, i) => {
                    return (
                      <>
                        <ProductItem
                          product={dataitem}
                          key={i}
                          spanClass={true}
                          addToCompare={() => compareContext.addToCompare(dataitem)}
                          addCart={() => handleAddProductToCart(dataitem)}
                          addWishlist={() => wishListContext.addToWish(dataitem)}
                          fileServerUrl={fileServerUrl}
                        />
                      </>
                    );
                  })
                }
              </Slider> */}
              <div className="page-select-btn"><Button className="page-select-btn1" onClick={searchLastPage}>Last Page</Button><span className="page-select-label">{pageNum} IN {pageCount}</span><Button className="page-select-btn2" onClick={searchNextPage}>Next Page</Button></div>
            </Col>
          </Row>
        </Container>
      </section>
    </Fragment>
  );
};

export default ParallaxSlider;
